package cn.com.guage.flink.transformation;

import java.util.Arrays;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import com.alibaba.fastjson.JSON;

import cn.com.guage.flink.domain.UserAction;

/**
 * 
 * @author yangdechao
 * map算子用法
 *
 */
public class MapTransformation {

	public static void main(String[] args) throws Exception {
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 输入: 用户行为。某个用户在某个时刻点击或浏览了某个商品，以及商品的价格。
        DataStreamSource<UserAction> source = env.fromCollection(Arrays.asList(
                new UserAction("userID1", 1293984000, "click", "productID1", 10),
                new UserAction("userID2", 1293984001, "browse", "productID2", 8),
                new UserAction("userID3", 1293984002, "click", "productID3", 10)
        ));
        source.print();
        // 转换: 商品的价格乘以8
        SingleOutputStreamOperator<String> result = source.map(new MapFunction<UserAction, String>() {
        	/**
			 * 
			 */
			private static final long serialVersionUID = 2872807733493736076L;

			public String map(UserAction value) throws Exception {

                int newPrice = value.getProductPrice() + 8;
                return JSON.toJSONString(new UserAction(value.getUserId(), value.getEventTime(), value.getEventType(), value.getProductId(), newPrice));
            }
        });

        result.print();
        env.execute();
	}

}
